package com.singlemountaintech.haogongjiang.qfd.ui.main.activity;

import android.os.Handler;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;

import com.framework.http.DefaultTransformer;
import com.jcodecraeer.xrecyclerview.ProgressStyle;
import com.jcodecraeer.xrecyclerview.XRecyclerView;
import com.singlemountaintech.haogongjiang.BuildConfig;
import com.singlemountaintech.haogongjiang.R;
import com.singlemountaintech.haogongjiang.http.JsonApiWrapper;
import com.singlemountaintech.haogongjiang.http.ProgressSubscriber;
import com.singlemountaintech.haogongjiang.model.response.GetPublishBuild;
import com.singlemountaintech.haogongjiang.model.response.PublishCraftsmanModel;
import com.singlemountaintech.haogongjiang.qfd.BaseActivityPresenter;
import com.singlemountaintech.haogongjiang.qfd.ui.main.delegate.AllListToobarDelegate;
import com.singlemountaintech.haogongjiang.utils.GlideUtil;
import com.singlemountaintech.haogongjiang.utils.LogUtils;
import com.singlemountaintech.haogongjiang.utils.TimeUtils;
import com.zhy.adapter.recyclerview.CommonAdapter;
import com.zhy.adapter.recyclerview.MultiItemTypeAdapter;
import com.zhy.adapter.recyclerview.base.ViewHolder;
import com.zhy.adapter.recyclerview.wrapper.EmptyWrapper;

import java.net.ConnectException;
import java.net.SocketTimeoutException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;

/**
 * 发布的工地
 */
public class MyPublishActivity extends BaseActivityPresenter<AllListToobarDelegate> {

    private static final String TAG = MyPublishActivity.class.getSimpleName();
    private List<GetPublishBuild.ObjectBean.ObjectElementsBean> list;
    private XRecyclerView mRecyclerView;
    private MultiItemTypeAdapter mAdapter;
    private EmptyWrapper emptyWrapper;
    protected Action mAction;
    protected int mPage = 1;
    protected int mTotalPages = 1;

    @Override
    protected Class<AllListToobarDelegate> getDelegateClass() {
        return AllListToobarDelegate.class;
    }

    @Override
    protected void bindEvenListener() {
        super.bindEvenListener();
        viewDelegate.setTitle("我发布的工地");
        mRecyclerView = viewDelegate.get(R.id.layout_xrl_body);
        mRecyclerView.setRefreshProgressStyle(ProgressStyle.BallPulse);
        mRecyclerView.setLoadingMoreProgressStyle(ProgressStyle.BallScaleMultiple);
        mAdapter = getAdapter();
        loadData();
        loadData1();
        loadData2();
        loadData1();
        mRecyclerView.setLoadingMoreProgressStyle(ProgressStyle.BallScaleMultiple);
        mRecyclerView.setLayoutManager(getLayoutManager());
        emptyWrapper = new EmptyWrapper(mAdapter);
        mRecyclerView.setAdapter(emptyWrapper);

        mRecyclerView.setLoadingListener(new XRecyclerView.LoadingListener() {
            @Override
            public void onRefresh() {
                //refresh data here
                MyPublishActivity.this.onRefresh();
                mRecyclerView.refreshComplete();
            }

            @Override
            public void onLoadMore() {
                // load more data here
                MyPublishActivity.this.onLoadMore();
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        mRecyclerView.loadMoreComplete();
                        mRecyclerView.scrollToPosition(mAdapter.getDatas().size() - 1);
                    }
                }, 1500);
            }
        });
    }

    public enum Action {
        REFRESH, LOADMORE
    }

    protected MultiItemTypeAdapter getAdapter() {
        list = new ArrayList<>();
        return new CommonAdapter<GetPublishBuild.ObjectBean.ObjectElementsBean>(this, R.layout.item_task_find_build_site, list) {

            @Override
            protected void convert(ViewHolder holder, final GetPublishBuild.ObjectBean.ObjectElementsBean bean, final int position) {
                holder.setText(R.id.tv_item_find_build_site_address1, bean.address);
                List<String> engineeringPicture = bean.engineeringPicture;
                if (engineeringPicture.size() > 0) {
                    GlideUtil.displayImg((ImageView) holder.getView(R.id.iv_item_find_build_site_unit), BuildConfig.SERVER_PICTURE + bean.engineeringPicture.get(0));
                }
                holder.setText(R.id.tv_item_find_build_site_unit1, bean.engineeringName);
                holder.setText(R.id.tv_item_find_build_site_time1, TimeUtils.stampToDate(bean.beginDate));
                holder.setText(R.id.tv_item_find_build_site_long1, String.valueOf(bean.duration) + "天");
                holder.setOnClickListener(R.id.ll_item_find_build_site, new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
//                        Intent intent = new Intent(MyPublishActivity.this, PublishPostActivity.class);
//                        intent.putExtra(Keys.VALUE, bean.id);
//                        startActivity(intent);
                    }
                });
            }
        };
    }

    @Override
    protected void refresh() {
        super.refresh();

        LogUtils.eNormal(TAG, "重新登录成功______________________-----");
        loadData();
    }

    private void loadData2() {
        JsonApiWrapper.getApiService().findByUsername()
                .compose(new DefaultTransformer<PublishCraftsmanModel>())
                .subscribe(new ProgressSubscriber<PublishCraftsmanModel>(this, false) {
                    @Override
                    public void onNext(PublishCraftsmanModel publishCraftsmanModel) {
                        if (publishCraftsmanModel.status == 20000) {

                        }
                    }

                });
    }

    private void loadData1() {
        JsonApiWrapper.getApiService().findByUsername()
                .compose(new DefaultTransformer<PublishCraftsmanModel>())
                .subscribe(new ProgressSubscriber<PublishCraftsmanModel>(this, false) {
                    @Override
                    public void onNext(PublishCraftsmanModel publishCraftsmanModel) {
                        if (publishCraftsmanModel.status == 20000) {

                        }
                    }

                });
    }

    protected void loadData() {
        JsonApiWrapper.getApiService().getBuildList(mPage)
                .compose(new DefaultTransformer<GetPublishBuild>())
                .subscribe(new ProgressSubscriber<GetPublishBuild>(this, true, "正在获取…") {
                    @Override
                    public void onNext(GetPublishBuild response) {
                        if (response.status == 20000) {
                            mTotalPages = response.object.totalPage;
                            int size = list.size();
                            List<GetPublishBuild.ObjectBean.ObjectElementsBean> objectElements = response.object.objectElements;
                            if (objectElements != null && objectElements.size() > 0) {
                                if (mAction == MyPublishActivity.Action.REFRESH) {
                                    clearData();
                                }
                                list.addAll(objectElements);
                                refreshData(list);
                            } else {
                                setEmptyView(null);
                            }
                        } else {
                            setEmptyView(null);
                        }
                    }

                    @Override
                    public void onError(Throwable e) {
                        super.onError(e);
                        setEmptyView(e);
                    }
                });
    }

    protected RecyclerView.LayoutManager getLayoutManager() {
        //默认是LinearLayoutManager
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);
        layoutManager.setOrientation(LinearLayoutManager.VERTICAL);
//        mRecyclerView.addItemDecoration(new SimpleDividerDecoration(this));
        return layoutManager;
    }

    public <P> void refreshData(List<P> datas) {
        if (mAdapter.getDatas() != null && !mAdapter.getDatas().isEmpty()) {
            //去重
            for (P data : datas) {
                if (!mAdapter.getDatas().contains(data))
                    mAdapter.getDatas().add(data);
            }
        } else {
            if (datas == null) {
                return;
            } else {
                mAdapter.getDatas().addAll(datas);
            }
        }
        emptyWrapper.notifyDataSetChanged();
    }

    public void clearData() {
        if (mAdapter != null && mAdapter.getDatas() != null) {
            mAdapter.getDatas().clear();
        }

    }

    public void onRefresh() {
        mPage = 1;
        mAction = MyPublishActivity.Action.REFRESH;
        loadData();
    }

    protected void onLoadMore() {
        mPage++;
        mAction = MyPublishActivity.Action.LOADMORE;
        if (mPage <= mTotalPages) {
            loadData();
        } else {
            Toast.makeText(this, getString(R.string.no_more), Toast.LENGTH_SHORT).show();
        }
    }

    protected View getEmptyView() {
        View emptyView = View.inflate(this, R.layout.claims_empty_view, null);
        return emptyView;
    }

    protected void setEmptyView(Throwable e) {
        if (emptyWrapper != null) {
            emptyWrapper.setEmptyView(getEmptyView(e));
            emptyWrapper.notifyDataSetChanged();
        }
    }

    protected View getEmptyView(Throwable e) {
        if (e != null && (e instanceof SocketTimeoutException || e instanceof ConnectException
                || e instanceof UnknownHostException)) {  //这个异常暂时归到网络中断状态上来， 具体根据需求再定
            View noNetworkView = View.inflate(this, R.layout.no_network_view, null);
            noNetworkView.findViewById(R.id.tv_reload).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    onRefresh();
                }
            });
            return noNetworkView;
        } else {
            return getEmptyView();
        }

    }

}
